package io.nekohasekai.sfa.database

import io.nekohasekai.sfa.bg.ProxyService
import io.nekohasekai.sfa.bg.VPNService
import io.nekohasekai.sfa.constant.ServiceMode

object Settings {

    var serviceMode  = ServiceMode.NORMAL
    var startedByUser = false

    const val ANALYSIS_UNKNOWN = -1
    const val ANALYSIS_ALLOWED = 0
    const val ANALYSIS_DISALLOWED = 1

    var disableMemoryLimit = false


    const val PER_APP_PROXY_DISABLED = 0
    const val PER_APP_PROXY_EXCLUDE = 1
    const val PER_APP_PROXY_INCLUDE = 2

    var perAppProxyEnabled = false
    var perAppProxyMode = PER_APP_PROXY_EXCLUDE
    var perAppProxyList = emptySet<String>()
    var perAppProxyUpdateOnChange = PER_APP_PROXY_DISABLED

    var systemProxyEnabled = true

    fun serviceClass(): Class<*> {
        return when (serviceMode) {
            ServiceMode.VPN -> VPNService::class.java
            else -> ProxyService::class.java
        }
    }

    suspend fun rebuildServiceMode(): Boolean {
        var newMode = ServiceMode.NORMAL
        try {
            if (needVPNService()) {
                newMode = ServiceMode.VPN
            }
        } catch (_: Exception) {
        }
        if (serviceMode == newMode) {
            return false
        }
        serviceMode = newMode
        return true
    }

    private suspend fun needVPNService(): Boolean {
//        val selectedProfileId = selectedProfile
//        if (selectedProfileId == -1L) return false
//        val profile = ProfileManager.get(selectedProfile) ?: return false
//        val content = JSONObject(File(profile.typed.path).readText())
//        val inbounds = content.getJSONArray("inbounds")
//        for (index in 0 until inbounds.length()) {
//            val inbound = inbounds.getJSONObject(index)
//            if (inbound.getString("type") == "tun") {
//                return true
//            }
//        }
//        return false
        return true
    }

}